#include "sync_utils.h"

Mutex::Mutex() {
	pthread_mutex_init(&_mutex,NULL);	
}

Mutex::~Mutex(){
	pthread_mutex_destroy(&_mutex);
}

void
Mutex::lock(){
	pthread_mutex_lock(&_mutex);
}

void
Mutex::unlock(){
	pthread_mutex_unlock(&_mutex);
}

Condition::Condition(){
	pthread_cond_init(&_cond, NULL);
}
Condition::~Condition(){
	pthread_cond_destroy(&_cond);
}

void
Condition::wait(Mutex& m) {
	pthread_cond_wait(&_cond, &(m._mutex));
}

void
Condition::signal(Mutex& m) {
	pthread_cond_signal(&_cond);
}

SpinLock::SpinLock(){
	pthread_spin_init(&_spinlock, PTHREAD_PROCESS_PRIVATE);
}

SpinLock::~SpinLock(){
	pthread_spin_destroy(&_spinlock);
}

void
SpinLock::lock(){
	pthread_spin_lock(&_spinlock);
}

void
SpinLock::unlock(){
	pthread_spin_unlock(&_spinlock);
}

Semaphore::Semaphore(){
	sem_init(&_sem, 0, 0);	
}

Semaphore::~Semaphore(){
	sem_destroy(&_sem);
}

int
Semaphore::P(long timeout){
	int ret;
	if (timeout <= 0)
		ret = sem_wait(&_sem);	
	else {
		struct timespec timespec;
		memset(&timespec, 0, sizeof(struct timespec));
		timespec.tv_sec = timeout;
		ret = sem_timedwait(&_sem, &timespec);
	}
	return ret;
		
}

int
Semaphore::get_value(){
	int value;
	sem_getvalue(&_sem, &value);
	return value;
}
void
Semaphore::V(){
	sem_post(&_sem);
}
